"use client";

import { Suspense, useCallback, useEffect, useRef, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import Navbar from "@/components/Navbar";
import { Descriptions, Divider, Skeleton, Spin } from "antd";
import dynamic from "next/dynamic";
import axiosInstance from "@/utils/axios";
import React from "react";


const HiglassWrapper = dynamic(() => import("@/components/HiglassWrapper"), {
    ssr: false, // 禁用服务器端渲染
    loading: () => <Spin size="large" />,
});


const HicViewer = dynamic(() => import("@/components/HicViewer"), {
    ssr: false,
});
const BigWigViewer = dynamic(() => import("@/components/BigWigViewer"), {
    ssr: false,
});

const HicViewerWithSuspense = (props: {
    hicFileURL: string;
    locus: string;
}) => (
    <Suspense fallback={<Skeleton active paragraph={{ rows: 8 }} />}>
        <HicViewer {...props} />
    </Suspense>
);

const BigWigViewerWithSuspense = (props: {
    bigWigUrlList: any[];
    locus: string;
}) => (
    <Suspense fallback={<Skeleton active paragraph={{ rows: 10 }} />}>
        <BigWigViewer {...props} />
    </Suspense>
);


export default function SpeciesDetail() {
    const { specie } = useParams();
    const [detail, setDetail] = useState<any>(null);
    const searchParams = useSearchParams();
    const id = searchParams.get("id");
    const [locus, setLocus] = useState<string>("");
    const browserInstance = useRef<HTMLDivElement | null>(null);
    const igvContainer = useRef<HTMLDivElement | null>(null);

    const bigWigUrlList = React.useMemo(
        () => [
            {
                type: "wig",
                format: "bigwig",
                url: "/hicproject/static/GBM_boundary_50k.bw",
                name: "50k",
            },
            {
                type: "wig",
                format: "bigwig",
                url: "/hicproject/static/GBM_compartment_100k.bw",
                name: "100k",
            },
            {
                type: "interaction",
                format: "bedpe",
                url: "/hicproject/static/merged_loops_restrict.bedpe",
                name: "bedpe",
            },
        ],
        []
    );

    const hicFileURL = "G1_new.hic";


    const fetchDetail = useCallback(async () => {
        const res = await axiosInstance.get(`/species/getDetail`, {
            params: { speciesId: id },
        });
        setDetail(res.data.data);
        let target = res.data.data;
        const targetRange = `${target.targetChromosome}:${target.targetGeneStart}-${target.targetGeneEnd}`;
        const humanRange = `${target.humanChromosome}:${target.humanGeneStart}-${target.humanGeneEnd}`;
        setLocus(humanRange);
    }, []);

    useEffect(() => {
        if (browserInstance.current) return; // 已经创建过就不重复
        if (igvContainer.current) return;

        fetchDetail();
    }, [id]);

    if (!detail) {
        return <Spin fullscreen size="large" />;
    }

    return (
        <Suspense>
            <div>
                <main className="container mx-auto p-8">
                    <h1 className="text-3xl font-bold mb-4">Specie Name</h1>
                    <Divider
                        orientation="start"
                        orientationMargin={0}
                        className="mt-8"
                    >
                        Species Info
                    </Divider>
                    {/* <p className="text-lg text-gray-700">Description</p> */}
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="Species Name">
                            {detail.targetName}
                        </Descriptions.Item>
                        <Descriptions.Item label="Gene">
                            {detail.targetGene}
                        </Descriptions.Item>
                        <Descriptions.Item label="Chromosome">
                            {detail.targetChromosome}
                        </Descriptions.Item>
                        <Descriptions.Item label="Gene Start">
                            {detail.targetGeneStart}
                        </Descriptions.Item>
                        <Descriptions.Item label="Gene End">
                            {detail.targetGeneEnd}
                        </Descriptions.Item>
                        <Descriptions.Item label="Gene Strand">
                            {detail.targetGeneStrand}
                        </Descriptions.Item>
                    </Descriptions>

                    <Divider
                        orientation="start"
                        orientationMargin={0}
                        className="mt-8"
                    >
                        HiGlass
                    </Divider>
                    <HiglassWrapper speciesNames={detail.targetName} />
                    <Divider
                        orientation="start"
                        orientationMargin={0}
                        className="mt-8"
                    >
                        Juicebox
                    </Divider>
                    <div
                        ref={browserInstance}
                        className="w-full p-1.5 rounded-md bg-[#f5f7f9] min-h-[900px]"
                    >
                        <HicViewerWithSuspense
                            hicFileURL={hicFileURL}
                            locus={locus}
                        />
                    </div>
                    <Divider
                        orientation="start"
                        orientationMargin={0}
                        className="mt-8"
                    >
                        BigWig
                    </Divider>
                    <div
                        ref={igvContainer}
                        className="w-full p-1.5 rounded-md bg-[#f5f7f9] min-h-[700px] mt-8 mb-8"
                    >
                        <BigWigViewerWithSuspense
                            bigWigUrlList={bigWigUrlList}
                            locus={locus}
                        />
                    </div>
                </main>
            </div>
        </Suspense>
    );
}
